package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.Department;
import com.example.chamberlainserver.Service.DepartmentService;
import com.example.chamberlainserver.mapper.DepartmentMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 部门服务实现类
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentServiceImpl.class);

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getAllDepartments() {
        return departmentMapper.getAllDepartments();
    }

    @Override
    public Department getDepartmentById(Integer id) {
        return departmentMapper.getDepartmentById(id);
    }

    @Override
    public Department getDepartmentByCode(String code) {
        return departmentMapper.getDepartmentByCode(code);
    }

    @Override
    @Transactional
    public boolean addDepartment(Department department) {
        // 如果status为null，设置默认值为true（启用）
        if (department.getStatus() == null) {
            department.setStatus(true);
        }
        
        // 验证parentId相关的业务逻辑
        if (department.getParentId() != null && department.getParentId() > 0) {
            Department parentDept = departmentMapper.getDepartmentById(department.getParentId());
            if (parentDept == null) {
                logger.error("父部门不存在，parentId: {}", department.getParentId());
                throw new IllegalArgumentException("父部门不存在");
            }
        }
        
        return departmentMapper.insertDepartment(department) > 0;
    }

    @Override
    @Transactional
    public boolean updateDepartment(Department department) {
        logger.info("DepartmentService开始更新部门: {}", department);
        
        try {
            // 验证parentId相关的业务逻辑
            if (department.getParentId() != null) {
                // 检查父部门是否存在
                if (department.getParentId() > 0) {
                    Department parentDept = departmentMapper.getDepartmentById(department.getParentId());
                    if (parentDept == null) {
                        logger.error("父部门不存在，parentId: {}", department.getParentId());
                        throw new IllegalArgumentException("父部门不存在");
                    }
                }
                
                // 防止将部门设置为自己的子部门（防止循环引用）
                if (department.getId() != null && department.getParentId().equals(department.getId())) {
                    logger.error("不能将部门设置为自己的父部门，departmentId: {}", department.getId());
                    throw new IllegalArgumentException("不能将部门设置为自己的父部门");
                }
                
                // 检查是否会形成循环引用（如果当前部门是目标父部门的祖先）
                if (department.getId() != null && isAncestorDepartment(department.getId(), department.getParentId())) {
                    logger.error("不能将祖先部门设为父部门，会形成循环引用。departmentId: {}, parentId: {}", 
                            department.getId(), department.getParentId());
                    throw new IllegalArgumentException("不能将祖先部门设为父部门");
                }
            }
            
            int result = departmentMapper.updateDepartment(department);
            logger.info("部门更新SQL执行结果: {}, 影响行数: {}", result > 0 ? "成功" : "失败", result);
            
            boolean success = result > 0;
            if (success) {
                logger.info("部门更新成功，部门ID: {}", department.getId());
            } else {
                logger.warn("部门更新失败，没有影响任何行，部门ID: {}", department.getId());
            }
            
            return success;
        } catch (Exception e) {
            logger.error("部门更新过程中发生异常，部门ID: {}, 异常信息: {}", department.getId(), e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional
    public boolean deleteDepartment(Integer id) {
        // 检查部门下是否有用户
        List<Integer> userIds = departmentMapper.getUserIdsByDepartmentId(id);
        if (userIds != null && !userIds.isEmpty()) {
            // 如果部门下有用户，不允许删除
            return false;
        }
        return departmentMapper.deleteDepartmentById(id) > 0;
    }

    @Override
    public List<Integer> getUserIdsByDepartmentId(Integer departmentId) {
        return departmentMapper.getUserIdsByDepartmentId(departmentId);
    }

    @Override
    public boolean isDepartmentCodeUnique(String code, Integer excludeId) {
        return departmentMapper.isDepartmentCodeUnique(code, excludeId);
    }

    @Override
    public boolean isDepartmentNameUnique(String name, Integer excludeId) {
        return departmentMapper.isDepartmentNameUnique(name, excludeId);
    }
    
    /**
     * 检查部门A是否是部门B的祖先（防止循环引用）
     * @param ancestorId 祖先部门ID
     * @param descendantId 后代部门ID
     * @return true表示是祖先关系
     */
    private boolean isAncestorDepartment(Integer ancestorId, Integer descendantId) {
        if (ancestorId == null || descendantId == null) {
            return false;
        }
        
        Department current = departmentMapper.getDepartmentById(descendantId);
        while (current != null && current.getParentId() != null) {
            if (ancestorId.equals(current.getParentId())) {
                return true;
            }
            current = departmentMapper.getDepartmentById(current.getParentId());
        }
        
        return false;
    }
}